<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card class="box-card">
      <!-- 头部搜索区域   栅格 -->
      <el-row :gutter="20">
        <!-- 搜索框 
        clearable清空搜索内容;clearable清空属性 clear在点击由clearable属性生成的清空按钮时触发-->
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <!-- 按钮 -->
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!--用户列表区域 -->
      <el-table :data="userList" stripe border>
        <!-- 索引列 -->
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <!-- 状态栏 -->
        <el-table-column label="状态">
          <!--  作用域插槽
          <template v-slot="{row}">
          <el-switch v-model="row.mg_state" active-color="#13ce66">
          开关 ，双向绑定布尔值 -->
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" active-color="#13ce66" @change="UserStateChange(scope.row)">
            </el-switch>
          </template>>
        </el-table-column>
        <!-- 操作列 -->
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <!-- 修改 -->
            <el-button type="primary" size="mini" icon="el-icon-edit" @click="editDialog(scope.row.id)"></el-button>
            <!-- 删除 -->
            <el-button type="danger" size="mini" icon="el-icon-delete-solid" @click="removeUserById(scope.row.id)">
            </el-button>
            <!-- 分配角色 enterable鼠标是否可进入到tooltip-->
            <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button type="warning" size="mini" icon="el-icon-s-tools"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 页码展示 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum" :page-sizes="[1, 2, 5, 10]" :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>

    </el-card>

    <!-- 添加用户信息提示框:visible.sync控制对话框的显示与隐藏 -->
    <el-dialog title="提示" :visible.sync="addDialogVisible" width="30%" @close="addDialogClosed">
      <!-- 内容主体 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addInfo">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑用户信息提示框 -->
    <el-dialog title="编辑用户信息" :visible.sync="editDialogVisible" width="50%" @close="editDialogClosed">
      <!-- 内容主体区域 -->
      <el-form ref="editFormRef" :rules="editFormRules" :model="editForm" label-width="70px">
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    data() {
      //   自定义验证邮箱规则
      var checkEmali = (rule, value, callback) => {
        const regEmali = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
        if (regEmali.test(value)) {
          return callback();
        }
        callback(new Error('请输入合法的邮箱'));
      }
      //   自定义验证手机号规则
      var checkMobile = (rule, value, callback) => {
        const regMobile = /^1[34578]\d{9}$/
        if (regMobile.test(value)) {
          return callback();
        }
        callback(new Error('请输入合法的手机号'));
      }
      return {
        //获取用户列表携带的数据
        queryInfo: {
          query: '',
          pagenum: 1, //当前页码
          pagesize: 2 //每页显示的条数
        },
        // 接收返回的数据
        userList: [], //用户列表
        total: 0, //总条数
        addDialogVisible: false, //添加弹出框的显示与隐藏
        editDialogVisible: false, //编辑弹出框的显示与隐藏
        addForm: { //添加用户数据
          username: '',
          password: '',
          email: '',
          mobile: ''
        },
        addFormRules: { //添加用户验证规则
          username: [{
              required: true,
              message: '请输入用户名称',
              trigger: 'blur'
            },
            {
              min: 3,
              max: 10,
              message: '用户名在3~10个字符之间',
              trigger: 'blur'
            }
          ],
          password: [{
              required: true,
              message: '请输入密码',
              trigger: 'blur'
            },
            {
              min: 6,
              max: 15,
              message: '用户名在6~15个字符之间',
              trigger: 'blur'
            }
          ],
          email: [{
              required: true,
              message: '请输入邮箱',
              trigger: 'blur'
            }, {
              validator: checkEmali, //自定义验证
              message: '邮箱格式不正确，请重新输入',
              trigger: 'blur'
            },
            // {  pattern: /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/,
            //    message: "邮箱不合法",
            //    trigger: 'blur'  } 
          ],
          mobile: [{
            required: true,
            message: '请输入手机号码',
            trigger: 'blur'
          }, {
            validator: checkMobile,
            message: '手机号码不正确，请重新输入',
            trigger: 'blur'
          }]
        },
        editForm: { //查询编辑用户信息
        },
        editFormRules: { //编辑验证规则
          email: [{
            required: true,
            message: '请输入邮箱',
            trigger: 'blur'
          }, {
            validator: checkEmali, //自定义验证
            message: '邮箱格式不正确，请重新输入',
            trigger: 'blur'
          }],
          mobile: [{
            required: true,
            message: '请输入手机号码',
            trigger: 'blur'
          }, {
            validator: checkMobile,
            message: '手机号码不正确，请重新输入',
            trigger: 'blur'
          }]
        }
      };
    },
    created() {
      // 渲染用户列表
      this.getUserList()
    },
    mounted() {

    },
    methods: {
      //   调用接口获取用户列表
      async getUserList() {
        const {
          data: res
        } = await this.$http.get("users", {
          params: this.queryInfo
        })
        if (res.meta.status !== 200) {
          return this.$message.console.error("获取用户列表失败");
        }
        // 获取成功将数据保存
        this.userList = res.data.users
        this.total = res.data.total
        // console.log(res)
      },
      //   每页显示的条数事件监听
      handleSizeChange(newSize) {
        // console.log(newSize);将每页展示条数值传递，重新发送请求进行渲染
        this.queryInfo.pagesize = newSize;
        this.getUserList()
      },
      //   页码值改变事件
      handleCurrentChange(newPage) {
        // console.log(newPage);根据更新的要展示的页码页,重新发送请求
        this.queryInfo.pagenum = newPage;
        this.getUserList()
      },
      //   监听用户状态的改变,并修改后台的状态
      async UserStateChange(userinfo) {
        // console.log(userinfo.mg_state);put一般是修改用户的数据
        const {
          data: res
        } = await this.$http.put(`users/${userinfo.id}/state/${userinfo.mg_state}`);
        if (res.meta.status !== 200) {
          userinfo.mg_state = !userinfo.mg_state //更新失败将页面状态修改会去
          return this.$message.error("更新状态失败")
        }
        this.$message.success("更新状态成功")
      },
      //   关闭添加框重置内容
      addDialogClosed() {
        this.$refs.addFormRef.resetFields()
      },
      //   点击添加按钮对表单进行预校验
      addInfo() {
        this.$refs.addFormRef.validate(async valid => {
          //   console.log(valid);验证失败
          if (!valid) return;
          //   验证成功调用接口添加用户数据
          const {
            data: msg
          } = await this.$http.post("users", this.addForm)
          if (msg.meta.status !== 201) return this.$message.error("添加用户失败")
          this.$message.success("添加用户成功")
          this.addDialogVisible = false //添加成功隐藏弹框
          this.getUserList() //重新渲染用户列表
        })
      },
      //   点击编辑修改用户信息
      async editDialog(id) {
        // console.log(id);作用域插槽将id传递,发起请求根据id获取用户数据
        const {
          data: msg
        } = await this.$http.get("users/" + id)
        if (msg.meta.status !== 200) return msg.$message.error("获取id失败")
        console.log(msg);
        this.editForm = msg.data //将数据传递
        this.editDialogVisible = true //显示编辑框
      },
      //   编辑表单重置
      editDialogClosed() {
        this.$refs.editFormRef.resetFields() //close事件关闭后将表单内容重置
      },
      // 修改用户信息并提交
      editInfo() {
        //   表单预验证
        this.$refs.editFormRef.validate(async valid => {
          if (!valid) return;
          //   调用接口修改用户信息
          const {
            data: res
          } = await this.$http.put("users/" + this.editForm.id, {
            email: this.editForm.email,
            mobile: this.editForm.mobile
          })
          if (res.meta.status !== 200) this.$message.error("更新用户信息失败")
          this.editDialogVisible = false
          this.getUserList()
          this.$message.success("更新用户信息成功")
        })
      },
      //   删除用户
      async removeUserById(id) {
        console.log(id);
        const result = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(error => error)
        // console.log(result);取消：cancel；确定：confirm
        if (result !== 'confirm') return this.$message.info("取消删除")
        // 调用接口删除
        const {
          data: msg
        } = await this.$http.delete("users/" + id)
        if (msg.meta.status !== 200) return this.$http.error("删除用户失败")
        this.$message.success("删除用户成功！")
        this.getUserList()
      }
    }
  };

</script>

<style scoped lang="less">

</style>
